import time

from PySide6.QtCore import QFile
from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QTreeWidgetItem, QHBoxLayout, QPushButton, QWidget, QMessageBox

from src.main.server.controller.server_info_controller import ServerInfoController
from src.main.server.controller.server_review_controller import ServerReviewController
from src.main.server.mapper.impl.server_info_impl import ServerInfoImpl


class ClientMainWindow:

    def __init__(self, main_window, username):
        self.username = username
        self._load_ui()
        self.main_window = main_window

    def _load_ui(self):
        path = "../../../qt_ui/client_main_window.ui"
        file = QFile(path)
        try:
            loader = QUiLoader()
            self.window = loader.load(file)
            self.window.pushButton.clicked.connect(self.close_window)
            self.window.lineEdit.setText(self.username)
            self.show_server_project_data()

        finally:
            file.close()

        if self.window:
            self.window.show()  # 显示独立窗口
        else:
            print("加载 UI 失败，请检查文件路径或内容")


    def show_server_project_data(self):
        """项目发布"""
        server_info_data = ServerInfoController().all_info()
        self.common_data(server_info_data, self.window.treeWidget_2)

    def common_data(self, data, TreeWidget):
        """数据展示复用函数"""

        def edit(f_data, button):
            print("我被触发啦~~~")
            print(f"{f_data}")
            # 插入审核数据
            status_code = ServerReviewController().insert(f_data, self.username)
            if status_code is None:
                # 使用 QMessageBox 显示提示信息
                QMessageBox.information(self.window, "提示", "无法重复报名")
                return

            print("插入审核数据成功")
            #报名
            status_code = ServerInfoController().addCount(f_data)
            if status_code is None:
                QMessageBox.information(self.window, "提示", "人额已满，无法报名")
                #手动实现事务回滚，删除上文插入的审核数据
                ServerReviewController().delete_by_serverName_volName((f_data, self.username))
                print("回滚成功")
                return
            print("更新项目人数成功")
            button.setText("已报名")  # 修改按钮文本


        TreeWidget.clear()  # 清除之前数据
        row_id = 1
        for row in data:
            first_col = row[0]
            item = QTreeWidgetItem(TreeWidget)
            col_idx = 1
            for text in row:
                item.setText(0, str(row_id))
                item.setText(col_idx, str(text))
                col_idx += 1
            # 创建按钮和布局
            button_layout = QHBoxLayout()
            edit_button = QPushButton("报名")
            edit_button.clicked.connect(lambda _, fc=first_col, btn=edit_button: edit(fc, btn))
            button_layout.addWidget(edit_button)
            button_layout.setContentsMargins(0, 0, 0, 0)
            # 创建 QWidget 作为容器
            button_container = QWidget()
            button_container.setLayout(button_layout)
            TreeWidget.setItemWidget(item, col_idx, button_container)
            row_id += 1

    def close_window(self):
        """关闭当前窗口"""
        self.window.close()

def client_main_window(self, username):
        self.login_window = ClientMainWindow(self, username)